import { useUserStore } from '@/stores/user'
import Request, { type HttpRequestConfig } from 'luch-request'

export const baseURL = 'https://consult-api.itheima.net'

const request = new Request({
  baseURL,
  timeout: 10000,
  custom: {
    loading: true,
  },
})

// 请求拦截器
request.interceptors.request.use(
  (request) => {
    // 请求加载提示，并启用透明遮罩层
    if (request.custom?.loading) {
      uni.showLoading({
        title: '加载中...',
        mask: true,
      })
    }

    // 添加token
    const token = useUserStore().token

    if (token) {
      request.header = {
        Authorization: `Bearer ${token}`,
      }
    }

    return request
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    // 关闭加载提示
    uni.hideLoading()
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: 'none',
      })

      return Promise.reject(res.data.message)
    }

    return res.data?.data
  },
  (error) => {
    // 关闭加载提示
    uni.hideLoading()
    if (error.data.code === 401) {
      // 401 表示未登录(后端同事定的规则)
      uni.showToast({
        title: error.data.message,
        icon: 'none',
      })
      // 清除 token
      const store = useUserStore()
      store.removeToken()
      store.removeUserInfo()
      // 替换到登录页
      uni.redirectTo({ url: '/pages/login/login' })
    }

    return Promise.reject(error)
  }
)

class Http {
  get<T>(url: string, config?: HttpRequestConfig) {
    return request.get<null, T>(url, config)
  }

  delete<T>(url: string, config?: HttpRequestConfig) {
    return request.delete<null, T>(url, config)
  }

  post<T>(url: string, data?: object, config?: HttpRequestConfig) {
    return request.post<null, T>(url, data, config)
  }

  put<T>(url: string, data?: object, config?: HttpRequestConfig) {
    return request.put<null, T>(url, data, config)
  }

  upload<T>(url: string, config?: HttpRequestConfig<UniApp.UploadTask>) {
    return request.upload<null, T>(url, config)
  }
}

const http = new Http()

export { request, http }
